package panda.li.navigation.callback;

import com.google.gson.Gson;
import com.zhy.http.okhttp.callback.Callback;

import java.lang.reflect.ParameterizedType;

import okhttp3.Call;
import okhttp3.Response;
import panda.li.navigation.base.MyApplication;
import panda.li.navigation.entity.BusInfo;
import panda.li.navigation.utils.JsonUtil;
import panda.li.navigation.utils.Result;
import panda.li.navigation.utils.ToastUtil;

public abstract class BaseCallBack<T> extends Callback<T> {


    @Override
    public T parseNetworkResponse(Response response, int id) throws Exception {
        String string = response.body().string();
        Class<T> tClass = (Class<T>)((ParameterizedType)getClass().getGenericSuperclass()).getActualTypeArguments()[0];
        //T info = new Gson().fromJson(string, tClass);
        T info = JsonUtil.fromJson(string, tClass);
        return info;
    }


    @Override
    public void onResponse(T response, int id) {
        Result base = (Result)response;
        if(base !=null){
            if((base.getStatus() != null &&  base.getStatus().intValue() == 200)
                    || (base.getCode() != null && base.getCode().intValue() == 0)){
                onSuccess(response, id);
            } else {
                ToastUtil.show(MyApplication.getInstance(), "操作失败！");
            }
        }

    }

    public abstract void onError(Call call, Exception e, int id);

    public abstract void onSuccess(T response, int id);
}
